package project.ekko;

import com.github.kwhat.jnativehook.GlobalScreen;
import project.ekko.listener.GlobalKeyboardListener;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.logging.*;

public class Launch {

    public static void main(String[] args) {
        initialLoggerFormat();
        Logger.getGlobal().info("Welcome to WOW assistant");
        try {
            GlobalScreen.registerNativeHook();
        } catch (Exception ex) {
            Logger.getGlobal().log(Level.SEVERE, "cannot register native hook! WOW assistant will be exit!", ex);
            return;
        }
        GlobalScreen.addNativeKeyListener(new GlobalKeyboardListener());
        Logger.getGlobal().info("The global keyboard event listener has been registered!");
    }

    private static void initialLoggerFormat() {
        class CustomFormatter extends Formatter {

            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

            final String logPattern = "\"[%s] [%s] %s%s\\n\"";

            @Override
            public String format(LogRecord record) {
                var message = formatMessage(record);
                var throwable = "";
                if (record.getThrown() != null) {
                    var sw = new StringWriter();
                    var pw = new PrintWriter(sw);
                    pw.println();
                    record.getThrown().printStackTrace(pw);
                    pw.close();
                    throwable = sw.toString();
                }
                return String.format(logPattern, record.getInstant().atZone(ZoneId.systemDefault()).format(formatter), Thread.currentThread().getName(), message, throwable);
            }
        }
        var handler = new ConsoleHandler();
        handler.setFormatter(new CustomFormatter());
        Logger.getGlobal().addHandler(handler);
        Logger.getGlobal().setUseParentHandlers(false);
    }

}
